import { useState, useEffect, useRef } from 'react';
import { Button, Space, Spin, Tree } from 'antd';
import { Table, MF, Modal } from 'com';
import menuStore from 'store/menu';
import { GetList, AddRole, UpdateRole, DeleteRole, AddMenus } from 'api/roles';
import { GetList as GetMenuList, GetMenusByRoleId } from 'api/menus';
import { asyncConfirm } from '@/utils/common';

/**
 * 表单配置项
 */
const options = {
    name: {
        title: '角色名称',
        max: 20,
        required: true
    }
}

export default () => {
    /**
   * 角色列表
   */
    const [list, setList] = useState([]);
    /**
     * 菜单列表
     */
    const [menus, setMenus] = useState([]);
    /**
     * 选中的key
     */
    const [checkedKeys, setCheckedKeys] = useState([]);
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * 获取菜单的loading
     */
    const [menuLoading, setMenuLoading] = useState(false);
    /**
     * 添加MF引用
     */
    const addMF = useRef();
    /**
     * 分配权限Modal引用
     */
    const assignModal = useRef();
    /**
     * 要修改的角色信息
     */
    const [role, setRole] = useState({});
    /**
     * 列
     */
    const cols = [
        {
            title: '角色名称',
            dataIndex: 'name',
            align: "center"
        },
        {
            title: '操作',
            align: 'center',
            width: 300,
            render: (text, row) => <Space>
                {menuStore.auth('updateRole') && <Button type="link" size="small" onClick={() => openAddMF({ ...row })}>编辑</Button>}
                {menuStore.auth('deleteRole') && <Button type="link" size="small" onClick={() => deleteRole(row)}>删除</Button>}
                {menuStore.auth('addRoleMenus') && <Button type="link" size="small" onClick={() => openAssign({ ...row })}>分配权限</Button>}
            </Space>
        }
    ]

    /**
     * 打开添加MF
     * @param {*} role 
     */
    const openAddMF = (role) => {
        setRole(role);
        addMF.current.show();
    }

    /**
     * 获取列表
     */
    const getList = async () => {
        try {
            setLoading(true);
            const list = await GetList();
            setList(list);
        } catch (error) { }
        setLoading(false);
    }

    menuStore.auth('roleList') && useEffect(() => {
        getList();
    }, []);

    /**
     * 提交
     * @param {*} values 
     */
    const confirm = async values => {
        try {
            addMF.current.start();
            await (role.id ? UpdateRole : AddRole)({ id: role.id, ...values });
            getList();
            addMF.current.hide();
        } catch (error) { }
        addMF.current.stop();
    }

    /**
     * 删除角色
     * @param {*} row 
     */
    const deleteRole = async row => {
        let res;
        try {
            res = await asyncConfirm(`您确定要删除【${row.name}】吗？`);
            await DeleteRole(row.id);
            getList();
        } catch (error) { }
        res && res.close();
    }

    /**
     * 打开分配窗体
     * @param {*} role 角色
     */
    const openAssign = async role => {
        setRole(role);
        assignModal.current.show();
        setMenuLoading(true);
        try {
            const [list, keys] = await Promise.all([GetMenuList(), GetMenusByRoleId(role.id)]);
            setCheckedKeys(keys);
            const menus = list.filter(c => c.pid === 0).map(c => ({
                title: c.name,
                key: c.id,
                children: list.filter(d => d.pid === c.id).map(d => ({
                    title: d.name,
                    key: d.id,
                    children: list.filter(e => e.pid === d.id).map(e => ({
                        title: e.name,
                        key: e.id
                    }))
                }))
            }));
            setMenus(menus);
        } catch (error) { }
        setMenuLoading(false);
    }

    /**
     * 选中数据
     * @param {*} checkedKeys 所有选中的值
     */
    const onCheck = checkedKeys => {
        setCheckedKeys(checkedKeys);
    }

    /**
     * 添加菜单
     */
    const addMenus = async () => {
        try {
            assignModal.current.start();
            await AddMenus({ role_id: role.id, menu_id: checkedKeys });
            getList();
            assignModal.current.hide();
        } catch (error) { }
        assignModal.current.stop();
    }

    return <div>
        <h3>角色列表</h3>
        <hr />
        {menuStore.auth('addRole') && <Button type="primary" onClick={() => openAddMF({})}>添加角色</Button>}
        <p></p>
        {menuStore.auth('roleList') && <Table cols={cols} data={list} loading={loading} />}
        {menuStore.auth('addRole', 'updateRole') && <MF onFinish={confirm} ref={addMF} options={options} title={role.id ? '修改角色' : '添加角色'} lw={80} values={role} />}
        {menuStore.auth('addRoleMenus') && <Modal onOk={addMenus} title="分配权限" ref={assignModal}>
            <Spin spinning={menuLoading}>
                <Tree checkable onCheck={onCheck} treeData={menus} checkedKeys={checkedKeys} />
            </Spin>
        </Modal>}
    </div>
}